package com.zp.servlet;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.zp.dao.UserDao;
import com.zp.dao.impl.UserDaoImpl;
import com.zp.domain.vo.UserVo;
import com.zp.utils.ResultUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet("/user/index")
public class IndexServlet extends HttpServlet {

    private UserDao userDao;
    private PrintWriter out;
    private int page;
    private int limit;
    private UserVo userVo;

    @Override
    public void init() throws ServletException {
        userDao = new UserDaoImpl();
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        response.setCharacterEncoding("UTF-8");

        HttpSession session = request.getSession();
        out = response.getWriter();
        Gson gson = new GsonBuilder().
                setDateFormat("yyyy-MM-dd")
                .create();

        String sno = (String)session.getAttribute("CURRENT_USER");
        if (sno != null && !sno.equals("")) {
            userVo = userDao.getUserVoBySno(sno);
        } else {

        }

        // 获取当前页码和限制
        page = Integer.parseInt(request.getParameter("page"));
        limit = Integer.parseInt(request.getParameter("limit"));

        try {
            List<UserVo> users = userDao.listUsersVo(page, limit);
            long maxPage = userDao.getNumOfUsers() / limit + 1;
            Map data = new HashMap();
            data.put("users", users);
            data.put("maxPage", maxPage);
            data.put("user", userVo);
            out.print(gson.toJson(ResultUtil.success(data)));
        } catch (Exception e) {
            e.printStackTrace();
            out.print(gson.toJson(ResultUtil.error("查询数据出错！")));
        }
    }

    @Override
    public void destroy() {
        super.destroy();
    }


}
